package com.leve.admin.repository;

import com.leve.admin.domain.Comment;
import com.leve.admin.domain.Post;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import static org.springframework.data.mongodb.core.query.Query.query;

@Repository
public class MonmentRepository {
    /**
     * mongodb space库
     */
    @Resource
    @Qualifier("cloudfsTemplate")
    private MongoOperations spaceMongoOperations;


    public List<Post> moments(PageRequest request, String statusId, String name) {
        Criteria criteria = new Criteria();
        criteria.and("total_voters").gte(0D);
        if (statusId != null && statusId.length() > 0) {
            criteria.and("sell_status").is(statusId);
        }
        if (name != null && name.length() > 0) {
            Pattern pattern = Pattern.compile("^.*" + name + ".*$", Pattern.CASE_INSENSITIVE);
            criteria.and("text").regex(pattern);
        }
        return spaceMongoOperations.find(query(criteria).with(new Sort(Sort.Direction.DESC, "created_date")).with(request), Post.class, "post");
    }


    public Post momentById(String pid) {
        Criteria criteria = new Criteria("_id").is(new ObjectId(pid));
        return spaceMongoOperations.findOne(query(criteria), Post.class, "post");
    }

    public List<Comment> findCommentsByPost(String id) {
        Criteria criteria = new Criteria("post_id").is(id);
        return spaceMongoOperations.find(query(criteria).with(new Sort(Sort.Direction.DESC, "created_date")), Comment.class, "comment");
    }

    public Map getPostNumber(String id) {
        Criteria criteria = new Criteria();
        criteria.and("created_by").is(id);
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),//查询条件
                //聚合统计，time_str，name2个字段聚合，count计数按最后一个字段计数
                Aggregation.group("created_by").count().as("postNumber")
        );
        AggregationResults<Map> results = spaceMongoOperations.aggregate(agg, "post", Map.class);
        return results.getUniqueMappedResult();
    }
}
